// config/config.go
package config

import (
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Config struct {
	Server struct {
		Address string
	}
	Database struct {
		User     string
		Password string
		Host     string
		Port     string
		Name     string
	}
	// 添加新的配置字段，比如用于AES加密的密钥
	AES struct {
		Key string
	}
	AI struct {
		AES struct {
			DataKey  string // 用于数据加密
			TokenKey string // 用于令牌加密
		}
		ALIYUN struct {
			KEY string
		}
	}
}

var (
	DB        *gorm.DB
	AppConfig Config
)

func Load() error {
	// 加载.env文件
	err := godotenv.Load()
	if err != nil {
		return fmt.Errorf("error loading .env file: %v", err)
	}

	// 加载服务器配置
	AppConfig.Server.Address = os.Getenv("SERVER_ADDRESS")
	if AppConfig.Server.Address == "" {
		AppConfig.Server.Address = ":8080" // 默认值
	} else {
		AppConfig.Server.Address = ":" + AppConfig.Server.Address
	}

	// 加载数据库配置
	AppConfig.Database.User = os.Getenv("DB_USER")
	AppConfig.Database.Password = os.Getenv("DB_PASS")
	AppConfig.Database.Host = os.Getenv("DB_HOST")
	AppConfig.Database.Port = os.Getenv("DB_PORT")
	AppConfig.Database.Name = os.Getenv("DB_NAME")

	// 加载AES密钥
	AppConfig.AES.Key = os.Getenv("AES_KEY")

	AppConfig.AI.ALIYUN.KEY = os.Getenv("ALIYUN_KEY")

	return nil
}

// 新增函数：获取AES密钥
func GetAESKey() []byte {
	return []byte(AppConfig.AES.Key)
}

func GetAiALIYunKEY() []byte {
	return []byte(AppConfig.AI.ALIYUN.KEY)
}

func InitDB() error {
	// 构建DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		AppConfig.Database.User,
		AppConfig.Database.Password,
		AppConfig.Database.Host,
		AppConfig.Database.Port,
		AppConfig.Database.Name)

	// 连接数据库
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("failed to connect database: %v", err)
	}

	log.Println("Database connected successfully!")
	return nil
}
